//
//  ClassificationViewController.m
//  BakeCenter
//
//  Created by 杨洋 on 15/9/23.
//  Copyright (c) 2015年 Baked. All rights reserved.
//

#import "ClassificationViewController.h"
#import "ClassificationCollectionViewCell.h"
#import "ClassificationCollectionReusableView.h"
#import "ClassificationModel.h"
#import "ClassificationListTableViewController.h"
@interface ClassificationViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) NSMutableArray *bigClassArray;

@property (nonatomic, strong) NSMutableArray *middleClassArray;

@property (nonatomic, strong) NSMutableArray *sectionNameArray;

@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;

@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation ClassificationViewController


-(void)addCollectionView
{
    //创建一个布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //设置集合视图行间距
    layout.minimumLineSpacing = 5;
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    //设置集合视图 每个item之间的间隔
    layout.minimumInteritemSpacing = 5;
    
    //设置集合视图 每个item大小
    layout.itemSize = CGSizeMake((kScreenWidth - 85 - 40)/3, 40);
    
    //设置集合视图 增广视图大小
    layout.headerReferenceSize = CGSizeMake(kScreenWidth - 85, 40);
    //创建一个集合视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(85, 40, kScreenWidth - 85, kScreenHeight - 200) collectionViewLayout:layout];
    
    //指定集合视图的数据源
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //系统提供的UICollectionView这个类是没有任何控件的,如果我们需要借助几何数突来展示信息 必须自己定义一个类继承自UICollectionView,来添加属于我们自己的控件 但是一旦创建了这个类后 使用之前必须让集合视图认识这个类 所以我们需要下面的注册过程
    [self.collectionView registerClass:[ClassificationCollectionViewCell class] forCellWithReuseIdentifier:@"myCell"];
    
    //注册一个增广视图
    [self.collectionView registerClass:[ClassificationCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myView"];
    [self.view addSubview: self.collectionView];
    self.collectionView.alwaysBounceVertical = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.scrollView.contentSize = CGSizeMake(85, 540);
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.collectionView.mas_left).offset(0);
        make.top.equalTo(self.searchBar.mas_bottom).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
}

#pragma mark ----- 数据解析 -----
- (void)reloadDataWithJason
{
    [LORequestManger GET:kClassUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        for (int i = 0; i < [dic[@"data"][@"classify"] count]; i++) {
            NSString *buttonName = dic[@"data"][@"classify"][i][@"name"];
            // 循环添加button
            [self addButton:buttonName i:i];
            NSDictionary *bigDic = [[NSDictionary alloc] initWithDictionary:dic[@"data"][@"classify"][i]];
            NSMutableArray *midArray = [NSMutableArray array];
            NSMutableArray *array = [NSMutableArray array];//放没有最里面一层的字典
            for (NSDictionary *MidleDic in bigDic[@"list"]) {
                NSMutableArray *smallArray = [NSMutableArray array];
                for (NSDictionary *smallDic in MidleDic[@"list"]) {
                    [smallArray addObject:smallDic];
                }
                [midArray addObject:smallArray];
                [array addObject:MidleDic];
            }
            [self.bigClassArray addObject:midArray];
            [self.middleClassArray addObject:array];
        }
        
        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];

    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.barTintColor = [UIColor whiteColor];
    self.searchBar.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.searchBar.tintColor = [UIColor grayColor];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜美食 如: 蛋糕 面包";
    [self.view addSubview:self.searchBar];
    [self addCollectionView];
    [self reloadDataWithJason];
    
}

- (void)addButton:(NSString *)buttonName i:(int)i
{
    UIButton *listButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    listButton.frame = CGRectMake(0, 50 * i, 85, 50);
    [listButton setTitle:buttonName forState:(UIControlStateNormal)];
    listButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    [listButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    listButton.titleLabel.font = [UIFont systemFontOfSize:16];
    listButton.tag = 1000 + i;
    [listButton addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    if (listButton.tag == 1000) {
        [listButton setBackgroundColor:[UIColor whiteColor]];
    }
    [self.scrollView addSubview:listButton];
}

-(void)buttonClick:(UIButton *)button{
    button.selected = YES;
    for (int i = 0; i < self.bigClassArray.count; i++) {
        UIButton *Button = (UIButton *)[self.view viewWithTag:1000 + i];
        if (button.tag - 1000 != i) {
            Button.selected = NO;
            Button.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
            [self.collectionView reloadData];
        }
        else{
            Button.selected = YES;
            Button.backgroundColor = [UIColor whiteColor];
        }
    }
    
}


- (NSMutableArray *)bigClassArray
{
    if (!_bigClassArray) {
        _bigClassArray = [[NSMutableArray alloc] init];
    }
    return _bigClassArray;
}

- (NSMutableArray *)middleClassArray
{
    if (!_middleClassArray) {
        _middleClassArray = [[NSMutableArray alloc] init];
    }
    return _middleClassArray;
}



- (NSMutableArray *)sectionNameArray
{
    if (!_sectionNameArray) {
        _sectionNameArray = [[NSMutableArray alloc] init];
    }
    return _sectionNameArray;
}

#pragma mark ----- collectionView代理方法 -----
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.bigClassArray.count != 0) {
        int number = 0;
        for (int i = 0; i < self.bigClassArray.count ; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:1000 + i];
            if (button.selected == YES) {
                number = i;
                
                break;
            }
        }
        NSLog(@"第%ld个分区的cell数 == %ld",section,[self.bigClassArray[number][section] count]);
        
        return [self.bigClassArray[number][section] count];
        
    }
    
    else{
        return 1;
    }

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.bigClassArray.count != 0) {
        int number = 0;
        for (int i = 0; i < self.bigClassArray.count ; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:1000 + i];
            if (button.selected == YES) {
                number = i;
            }
        }
        NSLog(@"分区数 == %ld",[self.bigClassArray[number] count]);
        return [self.bigClassArray[number] count];
    }
    else{
        return 1;
    }

}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ClassificationCollectionViewCell *  listCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];

    if (self.bigClassArray.count != 0) {
        int number = 0;
        for (int i = 0; i < self.bigClassArray.count ; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:1000 + i];
            if (button.selected == YES) {
                number = i;
            }
        }
        listCell.nameLabel.text = self.bigClassArray[number][indexPath.section][indexPath.row ][@"name"];
}

    
    return listCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassificationCollectionViewCell *cell = (ClassificationCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    ClassificationListTableViewController *classVC = [[ClassificationListTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
    classVC.urlStr = [cell.nameLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.navigationController pushViewController:classVC animated:YES];
}

#pragma mark ----- 增广视图 -----
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    ClassificationCollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myView" forIndexPath:indexPath];
    
    if (self.middleClassArray.count != 0) {
        int number = 0;
        for (int i = 0; i < self.bigClassArray.count ; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:1000 + i];
            if (button.selected == YES) {
                number = i;
            }
            
    }
        reusableView.headLabel.text = self.middleClassArray[number][indexPath.section][@"name"];
}
    return reusableView;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size = CGSizeMake(kScreenWidth - 85, 30);
    return size;
}


#pragma mark ----- 点击事件方法 -----
- (void)returnKeyBoard
{
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ------ searchBar代理方法 ------
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
            [cancelBtn addTarget:self action:@selector(returnKeyBoard) forControlEvents:(UIControlEventTouchUpInside)];
        }
    }
    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnKeyBoard)];
    [self.collectionView addGestureRecognizer:self.tapGesture];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [self.collectionView removeGestureRecognizer:self.tapGesture];
    [searchBar setShowsCancelButton:NO animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
